package com.wfh.aigenerator.core.handler;

import com.wfh.aigenerator.model.entity.User;
import com.wfh.aigenerator.model.enums.ChatHistoryMessageTypeEnum;
import com.wfh.aigenerator.service.ChatHistoryService;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/**
 * @Title: SimpleTextStreamHandler
 * @Author wangfenghuan
 * @Package com.wfh.aigenerator.core.handler
 * @Date 2025/8/5 21:29
 * @description: 普通文本流处理器
 */
@Slf4j
public class SimpleTextStreamHandler {

    /**
     * 处理传统的html和多文件html生成
     * @param originFlux
     * @param chatHistoryService
     * @param appId
     * @param loginUser
     * @return
     */
    public Flux<String> handle(Flux<String> originFlux,
                               ChatHistoryService chatHistoryService,
                               Long appId, User loginUser){
        StringBuilder aiResBuilder = new StringBuilder();
        return originFlux.map(msg -> {
            // 收集ai响应的内容
            aiResBuilder.append(msg);
            return msg;
        })
                .doOnComplete(() -> {
                    // 流式响应完成之后，添加ai消息到对话的历史
                    String aiResBuilderString = aiResBuilder.toString();
                    chatHistoryService.addChatMessage(appId, aiResBuilderString, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                })
                .doOnError(e -> {
                    // 如果ai回复失败，同样要记录错误的信息
                    String errorMsg = "ai回复失败：" + e.getMessage();
                    chatHistoryService.addChatMessage(appId, errorMsg, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                });
    }

}
